#!/usr/bin/python

# Copyright 2010 Mikko Rantanen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" MFilesFS Client

User mode program for querying information for the M-Files FS.
"""

import sys
import traceback
import client.cmds
import bus.channel as channel
from bus import BusError

args = sys.argv
exe = args.pop(0)

def print_usage():
    print 'Usage: mf <cmd> [parameters]'
    helps = {}
    namecol = 0
    for cmd in client.cmds.get_cmds():
        if len(cmd.name) > namecol:
            namecol = len(cmd.name)
        helps[cmd.name] = cmd.shorthelp()

    for n, h in helps.items():
        print "  %-*s - %s" % (namecol, n, h)

def print_help(cmd):
    print client.cmds.get_cmd(cmd).longhelp()

cmd = len(args) > 0 and args.pop(0) or 'help'

if cmd.lower() == 'help':
    cmd = len(args) > 0 and args.pop(0) or None

    if cmd:
        print_help(cmd)
    else:
        print_usage()

else:
    path = None
    param = None
    try:
        c = client.cmds.get_cmd(cmd)
        path, param = c.get_params(args)
    except:
        traceback.print_exc()
        print
        print_help(cmd)

    try:
        result = None
        with channel.Channel(path) as chan:
            result = chan.write(c.name, param, sync=True)

        c.output(result)
    except BusError, err:
        for l in err.message:
            print l

        for l in traceback.format_list(err.stack):
            print l.strip()




